<template>
   <section class="warnList" @click="treeBlurHide">
   	  	<el-form label-position="top" :inline="true" v-model="filter" class="demo-form-inline">
            <el-row>
                <el-col :span="4">
                    <el-form-item label="品牌名称:">
                        <el-autocomplete
					      class="inline-input"
					      v-model="filter.brandName"
					      :fetch-suggestions="querySearch"
					      placeholder="请选择品牌名称"
					      @select="handleSelect"
					      size="small"
					    ></el-autocomplete>
                    </el-form-item>
                </el-col>
                <!--<el-col :span="4">
                    <el-form-item label="数据监控类型:">
		                <el-select v-model="filter.control" size="small">
                            <el-option label="全部" value=""></el-option>
                            <el-option label="品牌监控" value="1"></el-option>
                            <el-option label="连接监控" value="-1"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>-->
                <el-col :span="4">
                    <el-form-item label="sku关键词:">
                        <el-autocomplete
					       class="inline-input"
					       v-model="filter.keyword"
					       :fetch-suggestions="querySearchSku"
					       :trigger-on-focus="false"
					       placeholder="请选择sku关键词"
					       @select="handleSelectSku"
					       size="small"
					    ></el-autocomplete>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="平台:">
                    	<el-input icon="caret-bottom" v-model="category.name" placeholder="选择搜索平台"  size="small"></el-input>
                    	<div @click.stop="category.showTree=!category.showTree" class="treeStyle">
                    		<div v-show="category.showTree" class="department-tree-select inline-tree" >
	                    	    <el-tree :data="category.data"
	                                style=""
	                                show-checkbox
	                                node-key="id"
	                                default-expand-all
	                                ref="searchTree"
	                                @check-change="handleCheckChange"
	                                :props="defaultProps">
	                            </el-tree>
                            </div>
                       </div>
                    </el-form-item>
                </el-col> 
                <el-col :span="4">
                    <el-form-item label="运营员:">
                        <el-input  class="hideSerach" :disabled="true" v-show="readOnly" placeholder="运营员" v-model="Operater" size="small" icon="el-icon-search"></el-input>
                        <el-input v-show="!readOnly" readonly placeholder="运营员" v-model="Operater" size="small" @focus="getOwnerData" icon="el-icon-search"></el-input>
                    </el-form-item>
                </el-col> 
            </el-row>
            <el-row>
                <el-col :span="24" class="action_col">
                    <el-form-item class="action_button_group_open">
                        <el-button size="small" type="primary" @click="empty"><i class="fa fa-trash-o fa-lg"></i> 清空筛选条件
                        </el-button>
                        <el-button size="small" type="primary" @click="submitSearch()" icon="el-icon-search">查询</el-button>
                    </el-form-item>
                </el-col>
           </el-row>  
            <el-row class="margin-table">
                <el-table :data="tableData1" border>
				    <el-table-column prop="brandName" label="品牌名称" align='center'></el-table-column>
				    <el-table-column prop="keyWordsName" label="sku关键词" align='center'></el-table-column>
				    <el-table-column prop="platTypeText"  label="平台" align='center' width="100"></el-table-column>
				    <el-table-column prop="whiteFakeCount" label="白名单假货商品数量" align='center'></el-table-column>
				    <el-table-column prop="fakeCount" label="非白名单假货商品数量" align='center'></el-table-column>						    
				    <el-table-column prop="fakePrice" label="假货价格区间" align='center'> </el-table-column>
				    <el-table-column prop="gmtCreateString" label="更新时间" align='center'></el-table-column>
				</el-table>
            </el-row>
            <el-row >
		        <el-pagination
		          class="maT-40"
                  @current-change="handleCurrentChange"
                  @size-change="handleSizeChange"
                  :current-page="currentPage"
                  :page-sizes="[10, 20, 50]"
                  :page-size="pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="totalCount">
		        </el-pagination> 
      		</el-row>
      		<!--*****************运营员框************-->
	        <el-dialog title="选择运营员" :visible.sync="dialogVisible" @close="closeOwnerDialog" >
	            <el-row style="margin-bottom: 20px" >
	                <el-col :span="12">
	                    <el-select v-model="ownerFilter.deptId" placeholder="请选择部门" size="small" @change="selectSeller">
	                        <el-option
	                          v-for="(item,index) in ownerOptions"
	                          :key="index"
	                          :label="item.name"
	                          :value="item.id">
	                        </el-option>
	                    </el-select>
	                </el-col>
	            </el-row>
	            <el-table ref="ownerMultipleTable" :data="ownerData" style="width: 100%" max-height="541" @selection-change="handleOwnerSelectionChange">
	                <el-table-column type="selection" width="55"></el-table-column>
	                <el-table-column prop="account" label="用户名" width="140"></el-table-column>
	                <el-table-column prop="name" label="用户姓名"></el-table-column>
	                <el-table-column prop="departmentName" label="部门"></el-table-column>
	            </el-table>
	            <el-row class="paging">
	                <el-pagination
	                    @current-change="ownerHandleCurrentChange"
	                    @size-change="ownerHandleSizeChange"
	                    :current-page="ownerPage.pageNum"
	                    :page-sizes="ownerPage.pageSizes"
	                    :page-size="ownerFilter.pageSize"
	                    layout="total, sizes, prev, pager, next, jumper"
	                    :total="ownerPage.total">
	                </el-pagination>
	            </el-row>
	
	            <el-row style="margin-top: 20px" >
	              <el-col :span="12">
	                <el-button type="primary" class="top_save" @click="onSubmit" size="small"><i class="fa fa-save"></i> 保存</el-button>
	              </el-col>
	              <el-col :span="12">
	                <el-button type="danger" class="top_close" @click="dialogVisible = false"  size="small"><i class="fa fa-sign-out"></i> 关闭</el-button>
	              </el-col>
	            </el-row>
	        </el-dialog>
   	  	</el-form>
   </section>
</template>

<script>
	import Vue from 'vue'
	import {mapGetters} from 'vuex'
    import {Button, Tabs, TabPane, TableColumn, Form, Table, FormItem, Option, Select, Input,Pagination,Row, Col,Tree,Dialog,Autocomplete} from 'element-ui'
//  import { FAKE_TOTALCOUNT, FAKE_CURRENTPAGE, FAKE_PAGESIZE } from '../../../store/mutation-types/warning/index.js'
	Vue.use(Tabs)
	Vue.use(Button)
	Vue.use(Select)
	Vue.use(Input)
	Vue.use(TabPane)
	Vue.use(Form)
	Vue.use(Option)
	Vue.use(FormItem)
	Vue.use(TableColumn)
	Vue.use(Table)
	Vue.use(Pagination)
	Vue.use(Row)
	Vue.use(Col)
	Vue.use(Tree)
	Vue.use(Dialog)
	Vue.use(Autocomplete)
    export default{
		components: {
			
        },
        head(){
            return {
                title: this.tabName,
                meta: [
                   { hid: 'collectList-warning1', name: 'collectList-warning1', content: 'collectList-warning1'}
                ]
            }
        },
        props:{
        	
        },
        data(){
        	return{
        		today:0,
        		tabName: '预警汇总列表',
        		readOnly: false,
        		dialogVisible: false,
        		Operater:'',//运营员
        		backOperater: '',
        		backId: '',
        		skuList:[],
        		listData:[],
        		checkTypes:[],
        		ownerOptions:[],
        		ownerData: [],
        		brandSelectId:'',
        		brandSelectName:'',
        		SkuSelectId:'',
        		SkuSelectName:'',
        		currentPage:1,
	      		pageSize:50,
	      		totalCount:0,
        		filter:{
	      			brandName:'',//品牌名称
	      			control:'',//数据监控
	      			keyword:'',//keyword
	      			platform:'',//平台
	      			usIds: ''//运营员id（数组）
      		    },
      		    ownerFilter: {
                    pageNum: 1,
                    pageSize: 10,
                    deptId: ''
                },
                user:{
                    deptId: '',
                    departmentName: ''
                },
                userData:{
                    userName: '',
                    userId: '',
                    deptCode: ''
                },
                ownerPage: {
                    pageSizes: [10, 20, 50],    // 每页可选条数列表,
                    total: 0,
                    pageNum: 1
                },
      		    tableData1: [],
		        defaultProps: {
                    children: 'children',
                    label: 'label',
                },
                category: {
                    name: '',
                    showTree: false,
                    data:[
	                    {
		                   	id:0,
		                   	label:'全部',
		                   	children: [{
					            id: 4,
					            label: '天猫'
					        }, {
					            id: 3,
					            label: '淘宝'
					        }, {
					            id: 1,
					            label: '京东'
					        }, {
					            id: 2,
					            label: '一号店'
					        }]
	                    }
                    ] 
                }   
        	}
        },
		mounted(){
			this.restaurants=this.loadAll();
			this.getUserData();
			this.changeTabs();
			if(process.BROWSER_BUILD) {
                let arr = this.pageTabsList;
                arr[arr.length-1].name = this.tabName;
                this.$store.commit('PAGETABSLIST',{data:arr})
            }
			if(this.$store.state.warning.todayFake0!={} && this.today==1){
				this.getStore(this.$store.state.warning.todayFake0)
			}
			if(this.$store.state.warning.todayFake1!={} && this.today==0){
				this.getStore(this.$store.state.warning.todayFake1)
			}
		},
		watch:{
            $route(m){
            	this.changeTabs();
            	if(this.$store.state.warning.todayFake0!={} && this.today==1){
					this.getStore(this.$store.state.warning.todayFake0)
			    }
				if(this.$store.state.warning.todayFake1!={} && this.today==0){
					this.getStore(this.$store.state.warning.todayFake1)
				}
            }
		},
		computed: {
            ...mapGetters({
               'pageTabsList': 'getPageTabsList',
//             'currentPage': 'currentPageFake',
//             'totalCount': 'totalCountFake',
//             'pageSize': 'pageSizeFake',
            })
        },
        created(){
//          this.getfakeList();
            if(process.BROWSER_BUILD) {
                if(this.pageTabsList[this.pageTabsList.length-1].name == 'CRM') {
                    let arr = this.pageTabsList;
                    arr[arr.length-1].name = this.tabName;
                    this.$store.commit('PAGETABSLIST',{data:arr})
                }  
            }
        },
        updated(){
        	
        },
		methods:{
			getStore(obj){
				this.brandSelectId=obj.brandSelectId1;
				this.filter.brandName =obj.brandName1;
	            this.SkuSelectId=obj.SkuSelectId1;
	            this.filter.keyword = obj.keyword1;
	            this.filter.usIds =obj.usIds1;
	            this.checkTypes=obj.checkTypes1;
	            this.category.name=obj.categoryName1;
	            this.Operater=obj.Operater1;
	            this.currentPage=obj.currentPageFake;
		    	this.pageSize=obj.pageSizeFake;
		    	this.totalCount=obj.totalCountFake;
			},
			setStore(obj){
				this.$store.commit(obj,{
	    			data:{
	    				brandSelectId1:this.brandSelectId,
		    			brandName1:this.filter.brandName,
		    			SkuSelectId1:this.SkuSelectId,
		    			keyword1:this.filter.keyword,
		    			usIds1:this.filter.usIds,
		    			checkTypes1:this.checkTypes,
		    			categoryName1:this.category.name,
		    			Operater1:this.Operater,
		    			currentPageFake :this.currentPage,
		    			pageSizeFake:this.pageSize,
		    			totalCountFake:this.totalCount
	    			}
	    		});
			},
			querySearch(queryString, cb) {
		        var restaurants = this.restaurants;
		        var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
		        // 调用 callback 返回建议列表的数据
		        cb(results);
		    },
		    querySearchSku(queryString, cb){
                if(queryString != "" && queryString != " "){
                    var params = {kwName: queryString}
                    this.$store.dispatch("getKeywordsListwarn",params).then((res)=>{
                        if(res && res.data.successed){
                            let list = res.data.data;
                            list.forEach((n,i)=>{
                                n.value = n.value
                            });
                            cb(list);
                        }
	                })
                }
            },
		    createFilter(queryString) {
		        return (restaurant) => {
		          return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
		        };
		    },
		    loadAll(){//模糊搜索受众名称
		    	this.$store.dispatch("getRightsBrandsList").then(res=>{
            		if(res && res.data.successed){
            			var list=res.data.data;
		      		    for(let i=0,len=list.length;i<len;i++ ){
		      		    	this.listData[i]={};
		      		    	this.listData[i].value=list[i].brandName;
		      		    	this.listData[i].id=list[i].id.toString();
		      		    }
	      		    }
	    		}).catch((error) => {})
            	return this.listData
		    },
		    closeOwnerDialog() {
                this.ownerFilter.deptId = '';
                this.ownerFilter.pageNum = 1;
                this.ownerFilter.pageSize = 10;
                this.dialogVisible = false;
            },
            getOwnerDeptment() {//获取销售员部门下拉框
                this.$store.dispatch('getOwnerDeptment')
                  .then((response) => {
                    if(!response){return}
                    var result = response.data;
                    if (result.code === 0) {
                        this.ownerOptions = result.data;
                    }
                })
            },
            getUserOwnerData() {//获取销售员列表
                this.$store.dispatch('getUserOwnerData',this.ownerFilter)
                  .then((response) => {
                    if(!response){return}
                    var result = response.data;
                    if (result.code === 0) {
                        this.ownerData = result.data.list;
                        this.ownerPage.total = result.data.total;
                        this.ownerPage.pageNum = result.data.pageNum;
                    }
                })
            },
            handleOwnerSelectionChange(selection) {//销售员多选
                let names = [];
                let ids = [];
                for (let i = 0; i < selection.length; i++) {
                    names.push(selection[i].name);
                    ids.push(selection[i].id)
                }
                this.ownerRows = ids;
                this.ownerSelection = names;
            },
            ownerHandleCurrentChange(val) {// 弹框销售员列表选择分页size
                this.ownerFilter.pageNum = val;
                this.getUserOwnerData();
            },
            ownerHandleSizeChange(val) {
                this.ownerFilter.pageSize = val;
                this.ownerFilter.pageNum = 1;
                this.getUserOwnerData();
            },
            onSubmit() {
            	if(this.ownerSelection==undefined){
            		this.ownerSelection=[];
            	}
            	if(this.ownerRows==undefined){
            		this.ownerRows=[];
            	}
                this.Operater = this.ownerSelection.join(',');
                this.filter.usIds = this.ownerRows.join(',');
                this.dialogVisible = false;
            },
            selectSeller(val) {
                this.getUserOwnerData();
            },
            getUserData() {
                this.$store.dispatch('getUserPersonalData')
                  .then((response) => {
                    if(!response){return}
                    var result = response.data;
                    if (result.code === 0) {
                        if(result.data && result.data.leaderType == 0) {
                            this.Operater = result.data.name;
                            this.backOperater = result.data.name;
                            this.backId= result.data.id;
                            this.filter.usIds = result.data.id;
                            this.readOnly = true;
                        }else {
                            this.readOnly = false;
                        }
                        this.user.deptId = result.data.deptId;
                        this.user.departmentName = result.data.departmentName;
                        this.userData.userName = result.data.name;
                        this.userData.userId = result.data.id;
                        this.userData.deptCode = result.data.deptCode;
                        this.getfakeList();
                    }
                })
            },
            getOwnerData() {
                this.dialogVisible = true;
                this.getUserOwnerData();
                this.getOwnerDeptment();
            },
		    handleSizeChange(val) {
		    	this.pageSize=val;
		    	if(this.today==1){ 
                	this.setStore('FAKE_TODAY_DATA')
                }
                if(this.today==0){ 
                	this.setStore('FAKE_HISTORY_DATA')
                }
				this.getfakeList()
		    },
		    handleCurrentChange(val) {
		    	this.currentPage=val;
		    	if(this.today==1){ 
                	this.setStore('FAKE_TODAY_DATA')
                }
                if(this.today==0){ 
                	this.setStore('FAKE_HISTORY_DATA')
                }
//		    	this.$store.commit('FAKE_CURRENTPAGE',{currentPage:val});
		        this.getfakeList()
		    },
		    handleSelectSku(item){
		    	this.SkuSelectId=item.id;
		    	this.SkuSelectName=item.value;
		    },
		    submitSearch(){
	    		this.getfakeList();
	    		if(this.today==1){
		    		this.setStore('FAKE_TODAY_DATA')
	    		}
	    		if(this.today==0){
	    			this.setStore('FAKE_HISTORY_DATA')
	    		}
	    	},
		    getfakeList(){//查询获取假货列表
		    	if(this.filter.brandName==''){
                	this.brandSelectId=''
                }
		    	if(this.brandSelectId){//避免品牌名称选中后更改问题
	    			if(this.filter.brandName!=this.brandSelectName){ this.brandSelectId =''}
	    		}
		    	if(this.SkuSelectId){//避免关键词选中后更改问题
	    			if(this.filter.keyword!=this.SkuSelectName){this.SkuSelectId=''}
	    		}
		    	this.$store.dispatch("fakeListwarn",{
		    		today:this.today,
		    		brandId:this.brandSelectId,
		    		brandNameLike:this.filter.brandName,
		    		keywordsId:this.SkuSelectId,
    				keywordsNameLike:this.filter.keyword,
    				platTypes:this.checkTypes,
    				operatorId:this.filter.usIds,
		    		pageNum: this.currentPage,
            		pageSize: this.pageSize
		    	}).then(res=>{
    				if(res && res.data.successed){
    					var result=res.data;
    					this.tableData1=result.data.list;
    					this.totalCount=result.data.total;
//  					this.$store.commit('FAKE_TOTALCOUNT',{totalCount:result.data.total});
    				}
    			}).catch((error) => {
    				this.tableData1=[]
    				this.totalCount=0
//  				this.$store.commit('FAKE_TOTALCOUNT',{totalCount:0});
    			})
		    },
		    //清空筛选条件
            empty(){
	    		this.filter = {
	    			brandName:'',//品牌名称
	      			keyword:'',//keyword
	      			platform:'',//平台
	    		}
	    		this.category.name='';
	    		this.SkuSelectId='';
	    		this.$refs.searchTree.setCheckedKeys([]);
	    		if(this.readOnly){
                    this.Operater = this.backOperater;
                    this.filter.usIds = this.backId;
                }else {
                    this.Operater = '';
                    this.filter.usIds = '' ;
                }
                if(this.today==1){this.$store.commit('FAKE_TODAY_DATA',{data:{}});}
                if(this.today==0){this.$store.commit('FAKE_HISTORY_DATA',{data:{}});}
	    	},
    	    changeOptionName(id){
    	    	switch(id){
    	    		case 4:return '天猫';break;
    	    		case 3:return '淘宝';break;
                    case 1:return '京东';break; 
                    case 2:return '1号店';break;
    	    	}
    	    },
    	     //隐藏客户分类
            treeBlurHide(){
                this.category.showTree = false;
            },
    	    handleCheckChange(data,checked) {
                this.category.name ='';
                var checkedId = this.$refs.searchTree.getCheckedKeys(data,true);
                this.checkTypes=checkedId;
                this.checkTypes=this.checkTypes.join(',')
                var checkedName = [];
                if(checkedId.length == this.category.data[0].children.length) {
                    this.category.name = '全部'
                }else {
                    for(var i=0;i<checkedId.length;i++){
                        checkedName.push(this.changeOptionName(checkedId[i]));
                    }
                    this.category.name = checkedName.join(' / ');
                }
            },
            handleSelect(item){//获取当前选中的品牌id		
		    	this.brandSelectId=item.id;
		    	this.brandSelectName=item.value;
		    },
		    changeTabs(){
		    	let url = window.location.href;
		        url = url.substring(url.lastIndexOf("="));
		        let tab = url.charAt(2);
		        if(tab==''){
		        	this.today=1
		        	this.tabName='今日预警汇总列表'
		        }else{
		        	this.today=0
		        	this.tabName='历史预警汇总列表'
		        }
		    }
		},
}
</script>

<style  lang="scss">
	.warnList{
		.el-form-item {
            width: 70%
        }
		.el-table__empty-block{width: 100% !important;}
		.hideSerach{
			.el-icon-search{display: none;}
		}
		margin-top:20px;
		.maT-40{margin-top:40px;}
		.el-tree-node__content{padding-left: 0 !important;}
		.treeStyle{
			position: absolute;top:3px;left:0;z-index: 10;
			width: 100%;height: 30px;
		}
		.paging {
            margin-top: 15px;
        }
		.top_close{
            float: left;
            margin-left: 20px;
            margin-top: 20px;
        }
        .top_close, .top_save{
            margin: 0 20px;
        }
        .top_save {
            float: right;
        }
	}
</style>